#include "teachform.h"
#include "MessageBox.h"
#include "ui_teachform.h"
#include "teachdialog.h"
#include "teachdelegate.h"

#include <QScroller>
#include <UrdfWidget.h>
#include <mainwindow.h>

#include <models/robotlist.h>
TeachForm::TeachForm(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::TeachForm)
{
    ui->setupUi(this);
    m_pTimer= new QTimer(this);
    connect(m_pTimer,&QTimer::timeout,this,&TeachForm::onTimeOut);
    m_pTeachModel=new TeachModel(this);
    connect(m_pTeachModel,&TeachModel::dataChanged,[=](){
        showTeachList(m_nCurIndex);
    });

    QString style= QString("QRadioButton::indicator:unchecked{\
                  width: %2px; \
                  height: %2px; \
                  margin-top:%3px; \
            border-image:url(:/images/uncheck.png);}\
            QRadioButton::indicator:checked{\
                      width: %2px; \
                             height: %2px; \
                                    margin-top:%3px; \
            border-image:url(:/images/check.png);}\
            QRadioButton{ \
            color: #FFFFFF; \
            font:%1px \"微软雅黑\";}").arg(int(18*g_xScale)).arg(int(20*g_xScale)).arg(int(0*g_xScale));

    ui->sustain_btn->setStyleSheet(style);
    ui->sustain_btn->setFixedSize(120*g_xScale,40*g_xScale);
    ui->fixed_btn->setStyleSheet(style);
    ui->fixed_btn->setFixedSize(120*g_xScale,40*g_xScale);

    style=QString("QPushButton {\
        background-color: #007BFF;\
        color: white; \
        border-radius: 5px; \
        margin :0px 10px 0px 0px;\
        font: %1px \"微软雅黑\" \
    } \
   QPushButton:pressed { \
        background-color: #0056b3; \
    }").arg(int(20*g_xScale));


    ui->title_label->setStyleSheet(QString("color:#FFFFFF;font: %1px \"微软雅黑\";").arg(int(20*g_xScale)));
    ui->add_btn->setStyleSheet(style);
    ui->preview_btn->setStyleSheet(style);
    ui->preview_btn->setFixedSize(100*g_xScale,40*g_xScale);
    ui->exec_btn->setStyleSheet(style);
    ui->exec_btn->setFixedSize(100*g_xScale,40*g_xScale);
    ui->info_lable->setStyleSheet(QString("color:#FFFFFF;font: %1px \"微软雅黑\";").arg(int(16*g_xScale)));


    initListViewStyle();
    initVideoStyle();
}
TeachForm::~TeachForm()
{
    delete ui;
}

void TeachForm::initVideoStyle()
{
    connect(RobotList::getInstance(), &RobotList::curRobotChanged, this, [&](Robot * pCurRobot, Robot * pLastRobot){
        if(pLastRobot)
            disconnect(pLastRobot,NULL, this,NULL);
        m_listVideoInfo.clear();
        m_vtVideoWidget.clear();
        if(pCurRobot)
        {
            QString btnStyle =QString("QPushButton {"
                               "    color: white;"  // 字体颜色设置为白色
                               "    padding: 5px;"  // 设置内边距，使文本不紧贴边框
                               "    border: none;"  // 去除边框
                               "    font:%1px \"微软雅黑\";"
                               "}"
                               "QPushButton:unchecked {"
                               "    background-color: gray;"  // 未选中时的背景色
                               "}"
                               "QPushButton:checked {"
                               "    background-color: #098CFF;"  // 选中时的背景色
                                       "}").arg(int(20*g_xScale));
            // 创建一个垂直布局
            QVBoxLayout *mainLayout = new QVBoxLayout(ui->video_widget);
            mainLayout->setContentsMargins(20*g_xScale,20*g_xScale,0,0);
            QHBoxLayout *buttonLayout = new QHBoxLayout;
            buttonLayout->setContentsMargins(0,0,0,0);
            buttonLayout->setSpacing(0);
            m_listVideoInfo=pCurRobot->lsVideo();
            bool bFirst=true;
            QButtonGroup * pGroup = new QButtonGroup(this);
            for(auto videoInfo:m_listVideoInfo)
            {
                TouchButton* btn = new TouchButton(videoInfo.strName);
                btn->setStyleSheet(btnStyle);
                btn->setFixedWidth(100*g_xScale);
                btn->raise();
                btn->setCheckable(true);
                buttonLayout->addWidget(btn);
                if(bFirst)
                {
                    bFirst=false;
                    btn->setChecked(true);
                }
                pGroup->addButton(btn);
                connect(btn, &QPushButton::toggled,[this,btn,videoInfo](bool checked){
                    if(checked)
                        {
                    QString clickedButtonText = btn->text();
                    if (clickedButtonText == videoInfo.strName) {
                        for(auto video:m_vtVideoWidget){
                            if(video->strUrl()==videoInfo.strUrl)
                            {
                                video->setParent(ui->video_widget);
                                video->setGeometry(0,0,ui->video_widget->width(),ui->video_widget->height());
                                video->lower();
                                video->setShowMax(false);
                                video->show();
                            }
                            else
                                video->hide();
                        }
                    }
                    }
                });
                VideoBase*videoWidget= MainWindow::getInstance()->pVideoWidget(videoInfo.strUrl);
                m_vtVideoWidget.push_back(videoWidget);
            }
            buttonLayout->addStretch();
            mainLayout->addLayout(buttonLayout);
            mainLayout->addStretch();
        }
    });
}

void TeachForm::showTeachList(int nIndex)
{
    Q_UNUSED(nIndex)
    //清理数据
    while( ui->teach_table_widget->rowCount()>0)
    {
        ui->teach_table_widget->removeRow(ui->teach_table_widget->rowCount()-1);
    }

    QVector<TeachData> vTeachData = m_pTeachModel->getTeachData(m_nCurIndex);
    for(int i=0;i<vTeachData.size();i++)
    {
        int row = ui->teach_table_widget->rowCount();
        ui->teach_table_widget->insertRow(row);
        QTableWidgetItem *idItem = new QTableWidgetItem(QString::number(row + 1));
        // 禁用编号的编辑功能
        idItem->setFlags(idItem->flags() & ~Qt::ItemIsEditable);
        idItem->setTextAlignment(Qt::AlignCenter);
        ui->teach_table_widget->setItem(row, 0, idItem);
        QString labelStyle=QString("QLabel{"
                             "background:transparent;"
                             "color:white;"
                             "font:%1px \"微软雅黑\";"
                             "border-color: #098CFF;"
                             "border-width:1px;}").arg(int(18*g_xScale));
        // 执行时间
        QLabel *execTimeItem = new QLabel(QString::number(vTeachData[i].execTime));
        //QIntValidator *execValidator = new QIntValidator(0, 9999999, execTimeItem);
        //execTimeItem->setValidator(execValidator);
        execTimeItem->setStyleSheet(labelStyle);
        execTimeItem->setAlignment(Qt::AlignCenter);
        ui->teach_table_widget->setCellWidget(row, 1, execTimeItem);
        // 等待时间
        QLabel *waitTimeItem = new QLabel(QString::number(vTeachData[i].waitTime));
        //QIntValidator *waitValidator = new QIntValidator(0, 9999999, waitTimeItem);
        //waitTimeItem->setValidator(waitValidator);
        waitTimeItem->setStyleSheet(labelStyle);
        waitTimeItem->setAlignment(Qt::AlignCenter);
        ui->teach_table_widget->setCellWidget(row, 2, waitTimeItem);
    }
}

void TeachForm::initListViewStyle()
{
    ui->exec_widget->setFixedWidth(250*g_xScale);
    ui->teach_list_view->setStyleSheet(QString("QListView {\
            background-color: transparent;   \
            border: none;\
            padding: %1px;\
            font: %2px \"微软雅黑\";\
            color: white;}\
            QListView::item {\
            height: 50px;}").arg(int(5*g_xScale)).arg(int(18*g_xScale)));

    ui->teach_list_view->setModel(m_pTeachModel);
    ui->teach_list_view->setItemDelegate(new TeachDelegate(this));
    ui->teach_list_view->setVerticalScrollMode(QListView::ScrollPerPixel);
    QScroller::grabGesture(ui->teach_list_view, QScroller::LeftMouseButtonGesture);
    ui->teach_list_view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    ui->teach_list_view->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    connect(ui->teach_list_view,&QListView::pressed, [&](const QModelIndex &index) {
        m_nCurIndex=index.row();
        showTeachList(m_nCurIndex);//选中示教展示数据
        // qDebug() << "Pressed item text:" << m_pTeachModel->data(index,TeachModel::NameRole).toString();
    });
    QString editStyle =QString("QLineEdit{"
                        "background:transparent;"
                        "color:white;"
                        "font:%1px \"微软雅黑\";"
                        "border:1px solid white;}"
                        "QLineEdit:focus {"
                        "    border: 1px solid #098CFF;"
                        "}").arg(int(18*g_xScale));
    QIntValidator *validator = new QIntValidator(0, 9999,  ui->lineEdit);
    ui->lineEdit->setValidator(validator);
    ui->lineEdit->setStyleSheet(editStyle);
    QString tableStyle = QString(
        "QTableWidget {"
        "    background-color: transparent;"
        "    border: 1px solid #3E3E40;"
        "    color: white;"
        "    gridline-color: #3E3E40;"
        "    font:%1px \"微软雅黑\";"
        "    border-top: none;"
        "}"
        "QTableWidget::item {"
        "    color: white;"
        "    background-color: transparent;"
        "    border-image: none;"
        "    font:%1px \"微软雅黑\";"
        "}"
        "QTableWidget::item:selected {"
        "    background-color: #444444;"
        "}"
        "QHeaderView {"
        "    background-color: #222222;"
        "    font-family: '微软雅黑';"
        "    border-image: none;"
        "}"
        "QHeaderView::section:horizontal {"
        "    background-color: transparent;"
        "    color: white;"
        "    border: 1px solid #3E3E40;"
        "    border-left: none;"
        "    border-top: none;"
        "    font:%1px \"微软雅黑\";"
        "    border-image: none;"
        "    height: 40px;"
        "}"
        "QScrollBar:vertical {"
        "    background-color: #2E2F31;"
        "}"
        "QScrollBar::handle:vertical {"
        "    background-color: #3E3E40;"
        "}"
        "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {"
        "    height: 0px;"
        "}").arg(int(18*g_xScale));
    ui->teach_table_widget->setFixedWidth(300*g_xScale);
    ui->teach_table_widget->setStyleSheet(tableStyle);
    ui->teach_table_widget->setVerticalScrollMode(QListView::ScrollPerPixel);
    QScroller::grabGesture(ui->teach_table_widget, QScroller::LeftMouseButtonGesture);
    ui->teach_table_widget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    ui->teach_table_widget->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    // 隐藏列表序号
    ui->teach_table_widget->verticalHeader()->setVisible(false);
    // 禁用水平表头的点击功能
    ui->teach_table_widget->horizontalHeader()->setSectionsClickable(false);   // 禁用表头点
    ui->teach_table_widget->horizontalHeader()->setFixedHeight(50*g_xScale);           // 固定表头高度;
    QStringList headers;
    // QVector<JOINT>  vJoint= getJointBody();
    // for (int i = 12; i < vJoint.size(); ++i)
    // {
    //     headers <<vJoint[i].strName;
    // }
    headers << "编号" <<  "执行时间" << "等待时间";
    ui->teach_table_widget->setColumnCount(headers.size());
    ui->teach_table_widget->setHorizontalHeaderLabels(headers);
    // 设置表内容高度
    ui->teach_table_widget->verticalHeader()->setDefaultSectionSize(40*g_xScale);
    // 设置列占满整个宽度
    ui->teach_table_widget->setColumnWidth(0, 50*g_xScale); // 编号列
    ui->teach_table_widget->horizontalHeader()->setSectionResizeMode(1,QHeaderView::Stretch);
    ui->teach_table_widget->horizontalHeader()->setSectionResizeMode(2,QHeaderView::Stretch);
    //ui->teach_table_widget->setItemDelegate(new NoFocusD)
    ui->teach_table_widget->setSelectionBehavior(QAbstractItemView::SelectRows);
}

void TeachForm::on_add_btn_clicked()
{
    //弹出添加页面
    TeachDialog dialog(TeachDialog::ADD_DIALOG,m_pTeachModel,0,MainWindow::getInstance());
    dialog.exec();
}

void TeachForm::showEvent(QShowEvent *event)
{
    Q_UNUSED(event)
    m_pTeachModel->resetData();
    ui->teach_list_view->setCurrentIndex(m_pTeachModel->index(0,0));
    UrdfWidget *pUrf= MainWindow::getInstance()->pUrdfWidget();
    if(pUrf)
    {
        pUrf->setParent(ui->urdf_widget);
        pUrf->show();
        pUrf->setGeometry(0,0,ui->urdf_widget->width(),ui->urdf_widget->height());
    }
    if(m_vtVideoWidget.size()>0)
    {
        m_vtVideoWidget[0]->setParent(ui->video_widget);
        m_vtVideoWidget[0]->setGeometry(0,0,ui->video_widget->width(),ui->video_widget->height());
        m_vtVideoWidget[0]->lower();
        m_vtVideoWidget[0]->setShowMax(false);
        m_vtVideoWidget[0]->show();
    }
    showTeachList(m_nCurIndex);
}

void TeachForm::calculateAverageNumbers(const QVector<float>& starts, const QVector<float>& ends, int n) {
    int size = qMin(starts.size(), ends.size());

    for (int j = 0; j <= n; ++j)
    {
        float* subResult=new float[31];
        memset(subResult,0,124);
        for (int i = 0; i < size; ++i) {
            float start = starts[i];
            float end = ends[i];
            if (n <= 0) {
                continue;
            }
            // 计算步长
            float step = (end - start) / n;
            // 从 start 开始，依次计算中间的数并添加到结果列表 从12开始是应为前面12个是腿的数据 示教不控制退
            float num = start + j * step;
            //腿的位置都是0，要留出来
            subResult[12+i]=num;
        }
        m_vJoints.append(subResult);
    }
}

void TeachForm::on_preview_btn_clicked()
{
    //处理数据
    UrdfWidget *pUrf= MainWindow::getInstance()->pUrdfWidget();
    if(!pUrf)
        return;
    if(ui->preview_btn->text()=="停止预览")
    {
        ui->preview_btn->setText("开始预览");
        m_pTimer->stop();
        pUrf->setBShowRobotData(true);
        for (auto joint:m_vJoints) {
            if(joint)
            {
                delete[] joint;
                joint=nullptr;
            }
        }
        m_vJoints.clear();
        m_nIndex=0;
    }
    else{
        pUrf->setBShowRobotData(false);
        QVector<TeachData> vTeachData = m_pTeachModel->getTeachData(m_nCurIndex);
        //去掉中间的手部分
        for(int i=0;i<vTeachData.size();i++)
        {
            vTeachData[i].jointData.remove(14,12);
        }
        for(int i=0;i<vTeachData.size()-1;i++)
        {
            calculateAverageNumbers(vTeachData[i].jointData,vTeachData[i+1].jointData,vTeachData[i].execTime/50);
            for(int j=0;j<+vTeachData[i].waitTime/50;j++)
                m_vJoints.append(nullptr);
        }
        m_pTimer->start(50);
        ui->preview_btn->setText("停止预览");
    }
}


void TeachForm::on_exec_btn_clicked()
{
    Robot* pCurRobot=RobotList::getInstance()->getCurRobot();
    if(pCurRobot)
    {
        if(ui->exec_btn->text()=="开始执行")
        {
            QString jsonData=m_pTeachModel->getTeachJson(m_nCurIndex);
            int nTime = 0;
            if(ui->fixed_btn->isChecked())
            {
                nTime = ui->lineEdit->text().toInt();
                if(nTime <= 0)
                {
                    warning(MainWindow::getInstance(),"循环次数必须大于0");
                    return;
                }
                //启动一个定时器监听是否执行完 如果是固定次数，持续不启动定时器
                QTimer::singleShot(m_pTeachModel->getCountTime(m_nCurIndex) * nTime,[=](){
                    ui->exec_btn->setText("开始执行");
                });
            }
            else{
                nTime=-1;
            }
            pCurRobot->startDemonstrate(jsonData,nTime);
            ui->exec_btn->setText("停止执行");
        }
        else{
            pCurRobot->stopDemonstrate();
            ui->exec_btn->setText("开始执行");
        }
    }
}

void TeachForm::onTimeOut()
{
    //根据计算出来的数据按时间显示url动作
    UrdfWidget *pUrf= MainWindow::getInstance()->pUrdfWidget();
    if(pUrf)
    {
        if(m_nIndex<m_vJoints.size())
        {
            if(m_vJoints[m_nIndex])
                pUrf->setArc(m_vJoints[m_nIndex]);
            m_nIndex++;
        }
        else
        {
            ui->preview_btn->setText("开始预览");
            m_pTimer->stop();
            pUrf->setBShowRobotData(true);
            for (auto joint:m_vJoints) {
                if(joint)
                {
                    delete[] joint;
                    joint=nullptr;
                }
            }
            m_vJoints.clear();
            m_nIndex=0;
        }
    }
}



void TeachForm::on_teach_table_widget_cellClicked(int row, int column)
{
    Q_UNUSED(column)
    QVector<TeachData> vTeachData = m_pTeachModel->getTeachData(m_nCurIndex);
    if(row < vTeachData.size())
    {
        int nPos = 0;
        QString str;
        str += getJointTypeText(LEFT_ARM_JOINT);
        str += ":\r\n   ";
        QVector<JOINT> joints = getJointByType(LEFT_ARM_JOINT);
        for(int i = 0; i < joints.size(); ++i)
        {
            if( nPos < vTeachData[row].jointData.size())
            {
                str+= QString("%1: %2°    ").arg(joints[i].strName).arg(vTeachData[row].jointData[nPos++]*180/M_PI, 0, 'f', 2);
                if(i==2)
                    str+= "\r\n   ";
                if(i==4)
                    str+= "\r\n   ";
            }
        }
        str += "\r\n";
        str += getJointTypeText(RIGHT_ARM_JOINT);
        str += ":\r\n   ";
        joints = getJointByType(RIGHT_ARM_JOINT);
        for(int i = 0; i < joints.size(); ++i)
        {
            if( nPos < vTeachData[row].jointData.size())
            {
                str+= QString("%1: %2°    ").arg(joints[i].strName).arg(vTeachData[row].jointData[nPos++]*180/M_PI, 0, 'f', 2);                if(i==2)
                    str+= "\r\n   ";
                if(i==4)
                    str+= "\r\n   ";
            }
        }
        str += "\r\n";
        str += "左工具";
        str += ":\r\n   ";
        for(int i = 0; i < 6; ++i)
        {
            if(nPos < vTeachData[row].jointData.size())
            {
                str+= QString("%1°   ").arg(vTeachData[row].jointData[nPos++]*180/M_PI, 0, 'f', 2);
            }
        }
        str += "\r\n";
        str += "右工具";
        str += ":\r\n   ";
        for(int i = 0; i < 6; ++i)
        {
            if( nPos < vTeachData[row].jointData.size())
            {
                str+= QString("%1°   ").arg(vTeachData[row].jointData[nPos++]*180/M_PI, 0, 'f', 2);
            }
        }
        str += "\r\n";
        str += getJointTypeText(WAIST_JOINT);
        str += ": \r\n  ";
        joints = getJointByType(WAIST_JOINT);
        for(int i = 0; i < joints.size(); ++i)
        {
            if(nPos> 0 && nPos < vTeachData[row].jointData.size())
            {
                str+= QString("%1: %2°    ").arg(joints[i].strName).arg(vTeachData[row].jointData[nPos++]*180/M_PI, 0, 'f', 2);
            }
        }
        str += "\r\n";
        str += getJointTypeText(HEAD_JOINT);
        str += ": \r\n  ";
        joints = getJointByType(HEAD_JOINT);
        for(int i = 0; i < joints.size(); ++i)
        {
            if(nPos> 0 && nPos < vTeachData[row].jointData.size())
            {
                str+= QString("%1: %2°    ").arg(joints[i].strName).arg(vTeachData[row].jointData[nPos++]*180/M_PI, 0, 'f', 2);
            }
        }
        str += "\r\n";
        ui->info_lable->setText(str);
    }
}


